import React, {useEffect, useState} from "react";
import {Button, Card, Col, Form, Input, message, Row, Select, Space, Tabs} from "antd";
import CodeEditor from "@/components/CodeEditor";
import {configBySql, generateApi} from "@/api/code";
import FieldConfigModal from "@/pages/code/FieldConfigModalProps";
import SqlModal from './SqlModal/index'
import ApiInfoMoDal from './ApiInfoModal/index'
import {getListProject, getProjectTemplate} from "@/api/project";
import {initConfig} from "@/config";
import {camelCase} from "lodash";

const Code: React.FC = () => {
    const [result, setResult] = useState({});
    const [form] = Form.useForm();
    const [projectList, setProjectList] = useState<{ value: number, label: string }[]>([]);
    const [selectedProject, setSelectedProject] = useState<number>();
    const [fieldInfoList, setFieldInfoList] = useState([
        {
            add: true,
            annotation: '',
            description: '',
            field: 'id',
            query: true,
            rpcType: '',
            type: 'string',
            update: true,
        },
    ]);
    const [modalVisible, setModalVisible] = useState(false);
    const [sqlModalVisible, setSqlModalVisible] = useState(false);
    const [apiInfoModalVisible, setApiInfVisible] = useState(false);
    const [apiInfoList, setApiInfoList] = useState([]);

    const className = Form.useWatch('className',form);

    useEffect(() => {
        fetchProjectList();
    }, []);

    useEffect(() => {
        if (projectList.length > 0) {
            const firstProjectId = projectList[0].value;
            setSelectedProject(firstProjectId);
            fetchProjectTemplateData(firstProjectId);
        }
    }, [projectList]);

    const handleChange = async (value) => {
        setSelectedProject(value)
        await fetchProjectTemplateData(value);
    };

    const fetchProjectTemplateData = async (id) => {
        if (!id) {
            message.error('请选择项目');
            return;
        }
        try {
            const res = await getProjectTemplate(id);
            // 空数组则提醒绑定模板
            if (res.data.length === 0) {
                message.error('所选项目请先绑定模板');
                return;
            }
            const formattedResult = res.data.reduce((acc, item) => {
                acc[item.code] = ''; // 初始化每个code对应的值为空字符串
                return acc;
            }, {} as { [key: string]: string });
            setResult(formattedResult);
        } catch (error) {
            message.error('获取项目数据失败');
            console.error('获取项目数据失败:', error);
        }
    };

    const fetchProjectList = async () => {
        try {
            const res = await getListProject({});
            const result = res.data.map((item) => ({
                value: item.id,
                label: item.code
            }));
            setProjectList(result);
        } catch (error) {
            message.error('获取项目数据失败');
            console.error('获取项目数据失败:', error);
        }
    };


    const fetchCodeApi = async () => {
        try {
            const templates = Object.keys(result);
            const res = await generateApi({
                binding: {
                    ...form.getFieldsValue(),
                    fieldInfoList: fieldInfoList,
                    apiInfoList: apiInfoList
                },
                templates: templates
            });
            if (res.code === 0) {
                setResult(res.data);
            } else {
                message.error(res.message);
            }
        } catch (e) {
            message.error(e.message);
        }
    };

    const handleOpenModal = () => setModalVisible(true);
    const handleCloseModal = () => setModalVisible(false);
    const handleSubmit = (fieldInfoList: any) => {
        setFieldInfoList(fieldInfoList);
        setModalVisible(false);
    };

    const handleOpenSqlModal = () => setSqlModalVisible(true);
    const handleCloseSqlModal = () => setSqlModalVisible(false);
    const handleSubmitSql = async (sql: string) => {
        const res = await configBySql({sql: sql})
        const fieldInfoList = res.data.fieldInfoList;
        form.setFieldsValue(res.data)
        setFieldInfoList(fieldInfoList)
        setSqlModalVisible(false);

    };

    const handleOpenApiInfoModal = () => setApiInfVisible(true);
    const handleCloseApiInfoModal = () => setApiInfVisible(false);
    const handleSubmitApiInfo = (apiInfoList: any) => {
        setApiInfoList(apiInfoList);
        setApiInfVisible(false);
    };

    const getCodeConfig = () => (
        <div style={{display: 'flex', alignItems: 'center'}}>
            <p style={{margin: 0, marginRight: 8}}>选择项目模板</p>
            <Select style={{width: 150}} showSearch options={projectList} value={selectedProject}
                    onChange={handleChange}/>
        </div>
    );

    // 当 className 变化时更新 classNameLowerCase
    useEffect(() => {
        if (className !== undefined) {
            form.setFieldsValue({
                classNameLowerCase: camelCase(className), // 转换为小写并更新字段
            });
        }
    }, [className]);

    return (
        <div>
            <Row>
                <Col span={8}>
                    <Card title="代码配置" extra={getCodeConfig()}>
                        <Form form={form} initialValues={initConfig}>
                            <Form.Item
                                name="className"
                                label="类名(大写)"
                            >
                                <Input placeholder="请输入" allowClear/>
                            </Form.Item>
                            <Form.Item
                                name="classNameLowerCase"
                                label="类名(小写)"
                            >
                                <Input placeholder="请输入" allowClear/>
                            </Form.Item>
                            <Form.Item
                                name="author"
                                label="作者"
                            >
                                <Input placeholder="请输入" allowClear/>
                            </Form.Item>
                            <Form.Item
                                name="description"
                                label="description"
                            >
                                <Input placeholder="请输入" allowClear/>
                            </Form.Item>
                            <Form.Item
                                name="controllerPackage"
                                label="controllerPackage"
                            >
                                <Input placeholder="请输入" allowClear/>
                            </Form.Item>
                            <Form.Item
                                name="daoPackage"
                                label="daoPackage"
                            >
                                <Input placeholder="请输入" allowClear/>
                            </Form.Item>
                            <Form.Item
                                name="serviceImplPackage"
                                label="serviceImplPackage"
                            >
                                <Input placeholder="请输入" allowClear/>
                            </Form.Item>

                            <Form.Item
                                name="servicePackage"
                                label="servicePackage"
                            >
                                <Input placeholder="请输入" allowClear/>
                            </Form.Item>
                            <Form.Item
                                name="entityPackage"
                                label="entityPackage"
                            >
                                <Input placeholder="请输入" allowClear/>
                            </Form.Item>
                            <Form.Item
                                name="primaryKeyType"
                                label="主键类型"
                            >
                                <Input placeholder="请输入" allowClear/>
                            </Form.Item>
                            <Form.Item
                                name="tableName"
                                label="表名"
                            >
                                <Input placeholder="请输入" allowClear/>
                            </Form.Item>
                            <Form.Item>
                                <Space direction="vertical" size="middle">
                                    <Row>
                                        <Button type="primary" block onClick={fetchCodeApi}>生成代码</Button>
                                    </Row>
                                    <Row>
                                        <Space>
                                            <Button onClick={() => {
                                                form.setFieldsValue(JSON.parse(localStorage.getItem('codeConfig') || '{}'));
                                                message.success('读取成功');
                                            }}>读取配置</Button>
                                            <Button onClick={() => {
                                                const values = form.getFieldsValue();
                                                localStorage.setItem('codeConfig', JSON.stringify(values));
                                                message.success('保存成功');
                                            }}>保存配置</Button>
                                            <Button onClick={handleOpenModal}>对象属性配置</Button>
                                            <Button onClick={handleOpenSqlModal}>SQL读取</Button>
                                            <Button onClick={handleOpenApiInfoModal}>接口读取</Button>
                                        </Space>
                                    </Row>
                                </Space>
                            </Form.Item>
                        </Form>
                    </Card>
                </Col>
                <Col span={16}>
                    <Tabs type="card" items={Object.keys(result).map(key => ({
                        label: key,
                        key: key,
                        children: <CodeEditor value={result[key]} language="java" height={650}/>
                    }))}/>
                </Col>
            </Row>
            <FieldConfigModal
                visible={modalVisible}
                onCancel={handleCloseModal}
                onSubmit={handleSubmit}
                initialValues={fieldInfoList}
            />

            <SqlModal
                visible={sqlModalVisible}
                onCancel={handleCloseSqlModal}
                onSubmit={handleSubmitSql}
            />

            <ApiInfoMoDal
                visible={apiInfoModalVisible}
                onCancel={handleCloseApiInfoModal}
                onSubmit={handleSubmitApiInfo}
            />
        </div>
    );
};

export default Code;